var tTimeTaken;
var tStartTime;
var tEndTime;
var tc;
var myID;

onmessage = function(event) {
	var message;
	var messageSent = event.data;


	switch (messageSent.cmd) {
		
		case 'init':
			message = "Initializing...";
			tc = messageSent.tc;
			myID = messageSent.parameter;
			postMessage(new MainMessage(tc, 'ready', myID));
			break;
		case 'file':
		    	message = myID + " Downloading File  :" + messageSent.parameter;    
			postMessage(new MainMessage(tc, 'echo', message));
			requestfile(messageSent.parameter);
		    	break;
	}

};

function MainMessage(tc, cmd, parameter) {
    this.tc = tc;
    this.cmd = cmd;
    this.parameter = parameter;
}

function get_appropriate_ws_url()
{
	var sURL = "ws://Edge2.NewLayerExtraction.sjsucmpe297.emulab.net:7681";
	return sURL;
}

function requestfile(filename) 
{
	
	var socket_fs;
	socket_fs = new WebSocket(get_appropriate_ws_url(), "file-server-protocol");		
	
	

	try {
		socket_fs.onopen = function() {
			tStartTime = new Date().getTime();			
			socket_fs.send(filename);					
		} 

		socket_fs.onmessage =function got_packet(msg) {							
			var fullfileName= filename; //document.getElementById("ws_filename").value;
			var patharray = fullfileName.split('/');
			var sfileName = patharray[patharray.length - 1] + "_" + myID;	
			//postMessage(new MainMessage(tc, 'echo', "Creating file - " + sfileName));			
			getFile(sfileName, msg);			
		}

		socket_fs.onclose = function() {			
			tEndTime = new Date().getTime();
			tTimeTaken = tEndTime - tStartTime;			
			postMessage(new MainMessage(tc, 'echo', "Download time - " + tTimeTaken + " milliseconds"));			
			postMessage(new MainMessage(tc, 'time', tTimeTaken));			
		}
		
	} catch(exception) {
		postMessage(new MainMessage(tc, 'error', exception));  
	}
	
}

function getFile(fileName, msg) {

	try 
	{
		self.requestFileSystemSync = self.webkitRequestFileSystemSync || self.requestFileSystemSync;
		var fs = requestFileSystemSync(TEMPORARY, 5*1024*1024);		
		var fileEntry = fs.root.getFile(fileName, {create: true, exclusive: true});					
		var fileWriter = fileEntry.createWriter(); 						   				
	
		fileWriter.seek(fileWriter.length);
		var builder = new this.WebKitBlobBuilder();
		builder.append(msg.data);
		var blob = builder.getBlob();
		fileWriter.write(blob);
	}
	catch(e)
	{
		errorHandler(e);
	}	
}

function errorHandler(e) 
{
  var msg = '';

  switch (e.code) 
 {
    case FileError.QUOTA_EXCEEDED_ERR:
      msg = 'QUOTA_EXCEEDED_ERR';
      break;
    case FileError.NOT_FOUND_ERR:
      msg = 'NOT_FOUND_ERR';
      break;
    case FileError.SECURITY_ERR:
      msg = 'SECURITY_ERR';
      break;
    case FileError.INVALID_MODIFICATION_ERR:
      msg = 'INVALID_MODIFICATION_ERR';
      break;
    case FileError.INVALID_STATE_ERR:
      msg = 'INVALID_STATE_ERR';
      break;
    default:
      msg = 'Unknown Error';
      break;
  };

  postMessage(new MainMessage(tc, 'error', msg));
}

